package jian.testcase.test;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

public class PackageUtil {

	public static void main(String[] args) {

		try {
			for (Class<?> claz : getClazInstances("jian.testcase.definition.impl")) {
				System.out.println(claz);
				System.out.println(claz.newInstance());
			}
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	public static Collection<Class<?>> getClazInstances(String packageName) {
		Collection<Class<?>> clazInstances = new LinkedList<Class<?>>();
		for (String clazName : getClassNames(packageName, true)) {
			try {
				clazInstances.add(Class.forName(clazName));
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		return clazInstances;
	}

	public static List<String> getClassNames(String packageName,
			boolean childPackage) {
		List<String> classNames = null;

		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		String packagePath = packageName.replace(".", "/");

		URL url = loader.getResource(packagePath);
		if (url != null) {
			String type = url.getProtocol();
			if ("file".equals(type)) {
				classNames = getClassNamesByFile(url.getPath(), packageName,
						true);
			} else if ("jar".equals(type)) {

			}
		}

		return classNames;

	}

	public static List<String> getClassNamesByFile(String filePath,
			String packageName, boolean childPackage) {
		List<String> classNames = new ArrayList<String>();

		File[] files = new File(filePath).listFiles();
		for (File file : files) {
			if (file.isDirectory()) {

			} else {
				String clazName = file.getName();
				if (clazName.endsWith(".class")) {
					classNames.add(packageName + "."
							+ clazName.substring(0, clazName.length() - 6));
				}
			}
		}
		return classNames;
	}
}
